import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as Joi from 'joi';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
import { NoteModule } from './note/note.module';
import configuration from './config/configuration';

@Module({
  imports: [
    ConfigModule.forRoot({
      //可以通过全局配置，这样在其他模块直接可以引入ConfigService,进行依赖注入
      isGlobal: true,
      ignoreEnvFile: true,
      load: [configuration],
      validationSchema: Joi.object({
        synchronize: Joi.boolean(),
        mysql: Joi.object({
          host: Joi.string().required(),
          port: Joi.number().required(),
          username: Joi.string().required(),
          password: Joi.string().required(),
          database: Joi.string().required(),
        }),
        jwt: Joi.object({
          secret: Joi.string().required(),
          expiresIn: Joi.number().required(),
          audience: Joi.string().required(),
        }),
      }),
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        return {
          type: 'mysql', // 指定使用的数据库类型为PostgreSQL
          host: configService.get<string>('mysql.host'),
          port: configService.get<number>('mysql.port'),
          username: configService.get<string>('mysql.username'),
          password: configService.get<string>('mysql.password'),
          database: configService.get<string>('mysql.database'), // 数据库名称
          autoLoadEntities: true, // 自动加载实体类，无需手动在模块中引入
          synchronize: configService.get<boolean>('synchronize'), // 自动同步数据库结构，生产环境中不建议使用
          timezone: '+08:00', // 设置时区
        };
      },
      inject: [ConfigService],
    }),
    AuthModule,
    UsersModule,
    NoteModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
